import style from "./index.module.css";
import { useState, useEffect } from "react";
import { getFriendListApi, addFriendApi } from "@/apis/friend";
import { searchApi } from "@/apis/search";
import { useSelector } from "react-redux";
import { TeamOutlined, UserOutlined } from "@ant-design/icons";
import { Avatar } from "antd";

const WSChat = () => {
  const [friends, setFriends] = useState<any[]>([]);
  const [isExpanded, setIsExpanded] = useState(false);
  const [activeFriend, setActiveFriend] = useState("");
  const [message, setMessage] = useState("");
  const [messages, setMessages] = useState<any>({});
  const [searchKeyword, setSearchKeyword] = useState("");
  const [searchResults, setSearchResults] = useState<any[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const ws = useSelector((state: any) => state.ws.ws);
  const user = useSelector((state: any) => state.user.profile);

  // 获取好友列表
  useEffect(() => {
    getFriendList();
  }, []);

  // WebSocket消息处理
  useEffect(() => {
    if (!ws) return;

    const handleWSMessage = (data: any) => {
      if (data.type === "MESSAGE") {
        const chatId = data.sender;
        const incomingMsg = {
          id: data._id,
          sender: data.sender,
          content: data.message,
          timestamp: new Date(data.timestamp),
          isMe: data.senderId === user.id,
        };

        setMessages((prev: any) => ({
          ...prev,
          [chatId]: [...(prev[chatId] || []), incomingMsg],
        }));
      }
    };

    ws.onMessage(handleWSMessage);

    return () => {};
  }, [ws]);

  const getFriendList = async () => {
    try {
      const res: any = await getFriendListApi();
      if (res.code === 0) setFriends(res.data.records);
    } catch (error) {}
  };

  // 发送消息
  const handleSendMessage = () => {
    if (!message.trim() || !activeFriend) return;

    const newMessage = {
      id: Date.now().toString(),
      sender: "me",
      content: message,
      timestamp: new Date(),
      isMe: true,
    };

    setMessages((prev: any) => ({
      ...prev,
      [activeFriend]: [...(prev[activeFriend] || []), newMessage],
    }));

    const friendship = friends.find(
      (friend: any) => friend.friendId === activeFriend
    );

    if (ws) {
      ws.send({
        type: "MESSAGE",
        message: message,
        receiver: [friendship.friendId],
      });
    }

    setMessage("");
  };

  // 搜索用户
  const handleSearch = async () => {
    if (!searchKeyword.trim()) return;

    setIsSearching(true);
    try {
      const res: any = await searchApi({
        type: 1,
        keyword: searchKeyword,
        value: [],
        pageParam: { page: 1, size: 10 },
      });
      if (res.code === 0) {
        const meId = user.id;
        res.data.records = res.data.records.filter(
          (user: any) => user.id !== meId
        );
        setSearchResults(res.data.records);
      }
    } catch (error) {
    } finally {
      setIsSearching(false);
    }
  };

  // 添加好友
  const handleAddFriend = async (friendId: string) => {
    try {
      const res: any = await addFriendApi(friendId);
      if (res.code === 0) {
        getFriendList();
        setSearchResults([]);
        setSearchKeyword("");
      }
    } catch (error) {}
  };

  // 判断是否是好友
  const isFriend = (friendId: string) => {
    return friends.some((user: any) => user.friendId === friendId);
  };

  useEffect(() => {
    document.body.style.overflow = isExpanded ? "hidden" : "";
    document.body.style.paddingRight = isExpanded ? "17px" : "";
    return () => {
      document.body.style.overflow = "";
      document.body.style.paddingRight = "";
    };
  }, [isExpanded]);

  return (
    <>
      <div className={style.chatIcon} onClick={() => setIsExpanded(true)}>
        <TeamOutlined />
      </div>

      {isExpanded && (
        <div className={style.overlay} onClick={() => setIsExpanded(false)} />
      )}

      <div
        className={`${style.chatContainer} ${isExpanded ? style.expanded : ""}`}
      >
        {isExpanded && (
          <div className={style.chatWindow}>
            <div className={style.header}>
              <h3>聊天</h3>
              <button
                className={style.closeButton}
                onClick={() => setIsExpanded(false)}
              >
                &times;
              </button>
            </div>

            <div className={style.searchSection}>
              <div className={style.searchInput}>
                <input
                  type="text"
                  value={searchKeyword}
                  onChange={(e) => setSearchKeyword(e.target.value)}
                  placeholder="搜索用户..."
                  onKeyDown={(e) => e.key === "Enter" && handleSearch()}
                />
                <button onClick={handleSearch} disabled={isSearching}>
                  {isSearching ? "搜索中..." : "搜索"}
                </button>
                {searchResults.length > 0 && (
                  <div className={style.searchResults}>
                    {searchResults.map((user: any) => (
                      <div key={user.id} className={style.searchResultItem}>
                        <div className={style.avatar}>
                          <Avatar
                            src={user.avatar}
                            icon={<UserOutlined />}
                            onError={() => {
                              return true;
                            }}
                          />
                        </div>
                        <div className={style.userInfo}>
                          <span>{user.username}</span>
                          {isFriend(user.id) ? (
                            <button
                              className={style.friendAddedButton}
                              disabled
                            >
                              已是好友
                            </button>
                          ) : (
                            <button
                              onClick={() => handleAddFriend(user.id)}
                              className={style.addButton}
                            >
                              添加好友
                            </button>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>

            <div className={style.chatContent}>
              <div className={style.friendList}>
                {friends.map((friend: any) => (
                  <div
                    key={friend.id}
                    className={`${style.friendItem} ${
                      activeFriend === friend.friendId ? style.active : ""
                    }`}
                    onClick={() => setActiveFriend(friend.friendId)}
                  >
                    <div className={`${style.avatar} ${style[friend.status]}`}>
                      <Avatar
                        src={friend.avatar}
                        icon={<UserOutlined />}
                        onError={() => {
                          return true;
                        }}
                      />
                    </div>
                    <div className={style.friendInfo}>
                      <span className={style.friendName}>
                        {friend.username}
                      </span>
                    </div>
                  </div>
                ))}
              </div>

              <div className={style.messageArea}>
                <div className={style.messages}>
                  {messages[activeFriend]?.map((msg: any) => (
                    <div
                      key={msg.id}
                      className={`${style.message} ${
                        msg.isMe ? style.myMessage : style.otherMessage
                      }`}
                    >
                      <div className={style.messageContent}>{msg.content}</div>
                      <div className={style.messageTime}>
                        {msg.timestamp.toLocaleTimeString([], {
                          hour: "2-digit",
                          minute: "2-digit",
                        })}
                      </div>
                    </div>
                  ))}
                  <div
                    ref={(el) => el?.scrollIntoView({ behavior: "smooth" })}
                  />
                </div>

                <div className={style.messageInput}>
                  <input
                    type="text"
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    placeholder={
                      activeFriend == "" ? "请选择聊天对象" : "输入消息..."
                    }
                    onKeyDown={(e) => e.key === "Enter" && handleSendMessage()}
                    disabled={activeFriend == ""}
                  />
                  <button onClick={handleSendMessage}>发送</button>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </>
  );
};

export default WSChat;
